package com.elinkway.infinitemovies.ui.activity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.webkit.DownloadListener;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebSettings.PluginState;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;

import com.elinkway.infinitemovies.bean.Lottery;
import com.elinkway.infinitemovies.lottery.LotteryManager;
import com.elinkway.infinitemovies.share.ShareCommonPopWindow;
import com.elinkway.infinitemovies.share.ShareJavascriptInterface;
import com.elinkway.infinitemovies.utils.LogUtils;
import com.le123.ysdq.R;

import java.lang.reflect.InvocationTargetException;

public class SpreadActivity extends BaseActivity {
    private WebView mSpreadView;
    private static final String onShareSuccessJS = "javascript:androidResult(\"success\")";
    private Lottery mLottery;
    private ShareCommonPopWindow mSharePopWin;
    private ProgressBar mProgressBar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_spread);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setIcon(R.drawable.actionbar_ic_activity);
//        getSupportActionBar().setHomeAsUpIndicator(getResources().getDrawable(R.drawable.finish_selector));
        mSpreadView = (WebView) findViewById(R.id.choujiang);
        mProgressBar = (ProgressBar) findViewById(R.id.spread_progress);
        mLottery = (Lottery) getIntent().getSerializableExtra("lottery");
        LotteryManager.getInstance().setLotteryEntered(mLottery);
        setListener();
        initWebView();
    }

    private void setListener() {}

    @SuppressLint("SetJavaScriptEnabled")
    private void initWebView() {
        mSharePopWin = new ShareCommonPopWindow(this);
//        mSharePopWin.setShareListener(this);
        mSpreadView.getSettings().setBuiltInZoomControls(false);
        mSpreadView.getSettings().setJavaScriptEnabled(true);
        mSpreadView.getSettings().setPluginState(PluginState.ON);
        mSpreadView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
        mSpreadView.setWebChromeClient(new SpreadChromeClient());
        mSpreadView.setWebViewClient(new MyWebViewClient());
        mSpreadView.setDownloadListener(mDownLoadListener);
        mSpreadView.addJavascriptInterface(new ShareJavascriptInterface(this, mSharePopWin),
                "_android");
        mSpreadView.loadUrl(mLottery.getUrl());
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.spread, menu);
        return super.onCreateOptionsMenu(menu);
    }
    @Override
    public void onBackPressed() {
        if (mSpreadView.canGoBack()) {
            mSpreadView.goBack();
        } else {
            finish();
        }
    }

    private class MyWebViewClient extends WebViewClient {

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            return true;
        }

         @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            mProgressBar.setVisibility(View.VISIBLE);
            mProgressBar.setProgress(0);
            super.onPageStarted(view, url, favicon);
        }

        @Override
         public void onPageFinished(WebView view, String url) {
         mProgressBar.setVisibility(View.GONE);
         super.onPageFinished(view, url);
         }

        @Override
        public void onReceivedError(WebView view, int errorCode, String description,
                String failingUrl) {
            super.onReceivedError(view, errorCode, description, failingUrl);
        }

    }

    private class SpreadChromeClient extends WebChromeClient{

        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            super.onProgressChanged(view, newProgress);
            mProgressBar.setProgress(newProgress);
        }
        
    }
//    @Override
//    public void onComplete() {
//    	UIs.showToast(R.string.toast_share_success);
//        mSpreadView.loadUrl(onShareSuccessJS);
//    }
//
//    @Override
//    public void onCancel() {
//        UIs.showToast(R.string.toast_share_canceled);
//
//    }
//
//    @Override
//    public void onFailed() {
//    	UIs.showToast(R.string.toast_share_failed);
//
//    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                finish();
                break;
            case R.id.action_refresh:
                mSpreadView.reload();
                break;
        }
        return super.onOptionsItemSelected(item);
    }



	@Override
	protected void onActivityResult(int arg0, int resultCode, Intent arg2) {
		super.onActivityResult(arg0, resultCode, arg2);
		LogUtils.i("share",arg0+" "+resultCode);
	}

    @Override
    protected void onPause() {
        super.onPause();
        try {
            mSpreadView.pauseTimers();
            mSpreadView.stopLoading();
            mSpreadView.getClass().getMethod("onPause").invoke(mSpreadView, (Object[]) null);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        try {
            mSpreadView.resumeTimers();

            mSpreadView.getClass().getMethod("onResume").invoke(mSpreadView, (Object[]) null);

        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
    }
    public static void launch(Context context, Lottery lottery){
    	Intent i = new Intent(context,SpreadActivity.class);
    	i.putExtra("lottery", lottery);
    	context.startActivity(i);
    }
    
    private DownloadListener mDownLoadListener = new DownloadListener() {

        @Override
        public void onDownloadStart(String url, String userAgent, String contentDisposition,
                String mimetype, long contentLength) {
            try {
                // 调用系统浏览器进行下载
                Uri uri = Uri.parse(url);
                Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                SpreadActivity.this.startActivity(intent);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };

}
